package cn.px.service.sb.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.github.pagehelper.PageHelper;
import cn.px.common.bean.AbstractPageResultBean;
import cn.px.common.exception.BusinessException;
import cn.px.common.model.UserInfo;
import cn.px.common.util.BeanConverterUtil;
import cn.px.common.util.IdGeneratorUtils;
import cn.px.common.util.SecurityUtils;
import cn.px.common.util.StringUtils;
import cn.px.dao.bean.MyPage;
import cn.px.dao.dto.part.PartInfoDTO;
import cn.px.dao.dto.sb.SbModelSpareBomDTO;
import cn.px.dao.dto.sqarepartmanage.SparePartInfoDTO;
import cn.px.dao.entity.part.PartInfo;
import cn.px.dao.entity.sb.SbModelSpareBom;
import cn.px.dao.entity.sqarepartmanage.SparePartInfo;
import cn.px.dao.mapper.sb.SbModelSpareBomMapper;
import cn.px.dao.util.CustomExcelImportUtil;
import cn.px.dao.vo.sb.SbModelSpareBomVO;
import cn.px.service.base.impl.BaseServiceImpl;
import cn.px.service.part.PartInfoService;
import cn.px.service.sb.SbModelSpareBomService;
import cn.px.service.sqarepartmanage.SparePartInfoService;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.web.multipart.MultipartFile;
import tk.mybatis.mapper.weekend.Weekend;
import tk.mybatis.mapper.weekend.WeekendCriteria;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * @Description 型号库-备件bom关联 service 实现类
 * @author 品讯科技
 * @date 2024-08
 * @Version Copyright (c) 2020,北京乾元坤和科技有限公司 All rights reserved.
 */
@AllArgsConstructor
@Service("sbModelSpareBomService")
public class SbModelSpareBomServiceImpl extends BaseServiceImpl<SbModelSpareBomMapper, SbModelSpareBom, SbModelSpareBomDTO> implements SbModelSpareBomService {
    private final  SparePartInfoService sparePartInfoService;
    private PartInfoService partInfoService;
    @Override
    public int batchDelete(List<String> ids) {
        Weekend<SbModelSpareBom> weekend = new Weekend<>(SbModelSpareBom.class);
        WeekendCriteria<SbModelSpareBom, Object> weekendCriteria = weekend.weekendCriteria();
        weekendCriteria.andIn(SbModelSpareBom::getId, ids);
        mapper.deleteByExample(weekend);
        return 1;
    }

    @Override
    public AbstractPageResultBean<SbModelSpareBomVO> selectPageList(SbModelSpareBomDTO record, int pageNum, int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        return new MyPage(mapper.selectVOList(record));
    }

    /**
     *
     *
     * @param dto
     */
    @Override
    public void relate(SbModelSpareBomDTO dto) {

    }

    @Override
    public void batchCancelRelate(SbModelSpareBomDTO dto) {

    }

    /**
     *
     * 已存在的备件，直接获取id
     * 不存在的要新增，然后获取id
     *
     * @param file
     * @param modelId
     */
    @Override
    public void importList(MultipartFile file, String modelId) {
        try {
            List<SparePartInfoDTO> items = CustomExcelImportUtil.importSpareBomList(file.getInputStream());
            if(!CollectionUtils.isEmpty(items)){
                for(SparePartInfoDTO item: items){
                    SparePartInfo checkItem = new SparePartInfo();
                    checkItem.setName(item.getName());
                    checkItem.setInitNo(item.getInitNo());
                    checkItem.setGgxh(item.getGgxh());
                    SparePartInfo lastItem = sparePartInfoService.getModelByModel(checkItem);
                    if(lastItem != null){
                        item.setId(lastItem.getId());
                    }else{
                        item.setCreatedTime(LocalDateTime.now());
                        item.setCreatedUserId("1");
                        lastItem = sparePartInfoService.saveModelByDTO(item);
                        item.setId(lastItem.getId());
                    }
                }
                List<SbModelSpareBomDTO> sbModelSpareBomDTOList = new ArrayList<SbModelSpareBomDTO>();
                // 排除已经存在的bom的
                for(SparePartInfoDTO item: items){
                    SbModelSpareBomDTO dto = new SbModelSpareBomDTO();
                    dto.setModelId(modelId);
                    dto.setSpareId(item.getId());
                    int count = super.getCountByDTO(dto);
                    if(count == 0){
                        dto.setNum(item.getMinStock());
                        dto.setId(IdGeneratorUtils.getObjectId());
                        sbModelSpareBomDTOList.add(dto);
                    }
                }
                super.saveModelListByDTO(sbModelSpareBomDTOList);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        LocalDateTime date = LocalDateTime.now();
        UserInfo user = SecurityUtils.getUserInfo();
    }

    @Override
    public List<SbModelSpareBomVO> selectVOList(SbModelSpareBomDTO dto) {
        return mapper.selectVOList(dto);
    }

    @Override
    public  List<SbModelSpareBomVO>  selectExportList(SparePartInfoDTO sparePartInfoDTO) {
        return mapper.selectExportList(sparePartInfoDTO);
    }

    @Override
    public List<SbModelSpareBomVO> selectExportList2(SparePartInfoDTO sparePartInfoDTO) {
        return mapper.selectExportList2(sparePartInfoDTO);
    }


    @Override
    public String copyFormSb(SbModelSpareBomDTO model) {
        PartInfoDTO partInfoDTO = new PartInfoDTO();
        partInfoDTO.setSbId(model.getSbId());
        partInfoDTO.setCopySbId(model.getCopySbId());
        String addPartResult = partInfoService.copyFormSb(partInfoDTO);

        SbModelSpareBomDTO record = new SbModelSpareBomDTO();
        record.setSbId(model.getSbId());
        List<SbModelSpareBomVO> list = mapper.selectVOList(record);

        SbModelSpareBomDTO copyRecord = new SbModelSpareBomDTO();
        copyRecord.setSbId(model.getCopySbId());
        List<SbModelSpareBomVO> copyList = mapper.selectVOList(copyRecord);
        List<SbModelSpareBomVO> addList = new ArrayList<SbModelSpareBomVO>();

        // 复制保养内容，刨除已经存在的：根据名称判断
        for(SbModelSpareBomVO copyCheckStandardVO:copyList){
            boolean find = false;
            for(SbModelSpareBomVO checkStandardVO:list){
                if(copyCheckStandardVO.getSpareId().equals(checkStandardVO.getSpareId())){
                    find = true;
                    break;
                }
            }
            if(!find){
                SbModelSpareBomVO checkStandardVO = copyCheckStandardVO;
                checkStandardVO.setId(IdGeneratorUtils.getObjectId());
                checkStandardVO.setSbId(model.getSbId());
                addList.add(checkStandardVO);
            }
        }

        // 设置新增保养内容的部位，根据部位名称进行判断
        PartInfoDTO partDTO = new PartInfoDTO();
        partDTO.setSbId(model.getSbId());
        List<PartInfo> partList = partInfoService.getModelListByDTO(partDTO);

        PartInfoDTO copyDTO = new PartInfoDTO();
        copyDTO.setSbId(model.getCopySbId());
        List<PartInfo> copyPartList = partInfoService.getModelListByDTO(copyDTO);
        if(CollectionUtil.isNotEmpty(addList)){
            for(SbModelSpareBomVO copyCheckStandardVO:addList){
                for(PartInfo copyPart:copyPartList){
                    if(copyPart.getId().equals(copyCheckStandardVO.getSbPartId())){
                        for(PartInfo part:partList){
                            if(part.getName().equals(copyPart.getName())){
                                copyCheckStandardVO.setSbPartId(part.getId());
                            }
                        }
                    }
                }
            }
            mapper.insertListforComplex(BeanConverterUtil.copyListProperties(addList, SbModelSpareBom.class));
        }
        return addPartResult + "，复制备件Bom：" + addList.size() + "个";
    }

    @Override
    public AbstractPageResultBean<SbModelSpareBom> selectPageInfo(SbModelSpareBomDTO record, int pageNum, int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        return new MyPage(mapper.selectVOList(record));
    }

    @Override
    public void modModelByDTO(SbModelSpareBomDTO model) {
        // 校验
        if(!model.getSpareId().equals(model.getOldSpareId())){
            SbModelSpareBomDTO queryDTO = new SbModelSpareBomDTO();
            queryDTO.setSpareId(model.getSpareId());
            if(StringUtils.isNotBlank(model.getSbId())){
                queryDTO.setSbId(model.getSbId());
            }
            int count = this.getCountByDTO(queryDTO);
            if(count != 0){
                throw new BusinessException("您将要修改的备件BOM，已经存在，请检查！备件名称: " + model.getSpareName());
            }
        }
        super.modModelByDTO(model);
    }
}
